<template>
	<view>
		<button @click=searchBlueTooth class="handAddBtn" size="mini">扫描蓝牙</button>
		<button @click="stopSearchBlue" class="handAddBtn" size="mini">停止扫描</button>
		<view class="item" v-for="item in bluetoothDeviceList" :key="item.deviceId" @click="connect(item)">
			<view>
				<text>id: {{ item.deviceId }}</text>
			</view>
			<view>
				<text>name: {{ item.name }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bluetoothDeviceList: [],
				deviceId: '',
				serviceId: '',
				characteristicId: '',
				result: '',
			}
		},
		mounted() {

		},
		onShow() {
			this.initBlueTooth()
		},
		onHide() {
			// 停止搜索
			this.stopSearchBlue()
		},
		methods: {
			// 初始化蓝牙
			initBlueTooth() {
				let that = this
				uni.openBluetoothAdapter({
					success(res) {
						console.log('初始化蓝牙成功');
						that.searchBlueTooth()
					},
					fail(err) {
						console.log('初始化蓝牙失败')
						console.error(err)
					}
				})
			},
			// 搜索蓝牙
			searchBlueTooth() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						console.log('开始搜索蓝牙');
						uni.onBluetoothDeviceFound(function(devices) {
							that.bluetoothDeviceList.push(devices.devices[0])
						})
					}
				})
			},
			// 连接蓝牙
			connect(data) {
				let that = this
				uni.createBLEConnection({
					deviceId: data.deviceId,
					success(res) {
						console.log('连接成功')
						uni.showToast('连接成功')
						uni.onBLEConnectionStateChange(function(res) {
							// 该方法回调中可以用于处理连接意外断开等异常情况
							console.log(
								`device ${res.deviceId} state has changed, connected: ${res.connected}`
								)
							// 如果断开链接，去重连
							if (!res.connected) {
								that.connect(data)
							}
						})
						// 停止搜索
						that.stopSearchBlue()
						// 获取已经链接的设备
						that.getConnectedDevice()
					},
					fail(err) {
						console.log('连接失败')
						console.error(err)
					}
				})
			},
			// 获取已经链接的设备
			getConnectedDevice() {
				let that = this
				uni.getConnectedBluetoothDevices({
					success(res) {
						console.log(res);
						console.log('获取已连接的设备');
						that.deviceId = res.devices[0].deviceId
						// 这里需要延时1ms
						setTimeout(() => {
							that.getBlueToothService(res.devices[0].deviceId)
						}, 1500)
					}
				})
			},
			// 获取蓝牙设备所有服务
			getBlueToothService(deviceId) {
				let that = this
				console.log(deviceId)
				uni.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					success(res) {
						console.log('device services:', res)
						console.log('device services:', res.services)
						that.serviceId = res.services[3].uuid
						that.getBLEDeviceCharacteristics()
					}
				})
			},
			// 获取蓝牙设备某个服务中所有特征值
			getBLEDeviceCharacteristics() {
				let that = this
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId, // 设备ID
					serviceId: that.serviceId, // 服务UUID
					success(res) {
						console.log(res)
						that.characteristicId = res.characteristics[0].uuid
						that.notifyBLECharacteristicValueChange()
					},
					fail(err) {
						console.error(err)
					}
				})
			},
			// 启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值
			notifyBLECharacteristicValueChange() {
				let that = this
				uni.notifyBLECharacteristicValueChange({
					deviceId: that.deviceId, // 设备ID
					serviceId: that.serviceId, // 服务UUID
					characteristicId: that.characteristicId, // 特征值
					state: true,
					success(res) {
						that.listenValueChange()
					},
					fail(err) {
						console.error(err)
					}
				})
			},
			// 开始监听设备值变化
			listenValueChange() {
				console.log('开始监听设备值变化');
				let that = this
				uni.onBLECharacteristicValueChange(res => {
					let beforeNum1 = res.value
					const uint8View = new Uint8Array(beforeNum1);
					let isSuccess = uint8View[6]
					if (isSuccess == 1) {
						console.log(112233);
						if (uint8View[7] < 0) {
							that.result += 256
						} else {
							that.result = (uint8View[7] + 256) / 10.0
						}
					}
					console.log(that.result, '正确结果');
				})
			},
			stopSearchBlue() {
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
					}
				})
			},

		}
	}
</script>

<style>
	.item {
		box-sizing: border-box;
		padding: 10rpx;
		font-size: 16rpx;
		border-bottom: 1px solid #ccc;
	}
</style>